package dm;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;

import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import database.DBConnection;
import bean.shoppingCard.ProductDetail;

public class ProductDM {
	
	public ProductDetail openProduct(int proId,int userId) throws Exception{
		
		Connection con = DBConnection.getConnection();
		CallableStatement statement = null;
		ResultSet res = null;

		try {
			statement = con.prepareCall("{?=call PRODUCT_PKG.GET_PRODUCT(?)}");
			statement.registerOutParameter(1, OracleTypes.CURSOR);
			statement.setInt(2,proId);
			statement.execute();
			OracleCallableStatement ocstm = (OracleCallableStatement) statement;
			res = ocstm.getCursor(1);
			
			while(res.next()){
				ProductDetail product =  new ProductDetail(res.getInt(1), res.getString(2),res.getString(3),res.getDouble(5), res.getString(4),res.getInt(7),res.getString(8), res.getDouble(6));
				statement.close();
				
				statement = con.prepareCall("{?=call LOG_PKG.PRODUCT_OPEN_LOG(?,?)}");
				statement.setInt(1,userId);
				statement.setInt(2,proId);
				statement.execute();
				
				statement.close();
				DBConnection.closeConnection(con);
				return product;
			}
			DBConnection.closeConnection(con);
			return null;
			
		} catch (Exception e) {
			try {
				statement.close();
			} catch (Exception exception) {
			}
			try {
				DBConnection.closeConnection(con);
			} catch (Exception exception) {
			}
			throw e;
		}
	}
	
	public void closeProduct(int proId,int userId) throws Exception{
		
		Connection con = DBConnection.getConnection();
		CallableStatement statement = null;

		try {
				statement = con.prepareCall("{?=call LOG_PKG.PRODUCT_CLOSE_LOG(?,?)}");
				statement.setInt(1,userId);
				statement.setInt(2,proId);
				statement.execute();
				
				statement.close();
				DBConnection.closeConnection(con);
			
		} catch (Exception e) {
			try {
				statement.close();
			} catch (Exception exception) {
			}
			try {
				DBConnection.closeConnection(con);
			} catch (Exception exception) {
			}
			throw e;
		}
		
	}

}
